package org.nicocube.airain.app.server;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import org.nicocube.airain.app.client.AppGCService;
import org.nicocube.airain.app.client.domain.AppGameCharacter;
import org.nicocube.airain.domain.client.exception.DomainException;
import org.nicocube.airain.domain.server.dao.DomainDAO;
import org.nicocube.airain.domain.server.storable.GameCharacterStorable;
import org.nicocube.airain.domain.server.storable.GameCharacterStorableDAO;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class AppGCServiceImpl extends RemoteServiceServlet implements AppGCService {
	private static final Logger log = Logger.getLogger(AppGCServiceImpl.class.getName());

	private static final long serialVersionUID = 1L;

	private GameCharacterStorableDAO gameCharacterStorableDAO;

	public AppGCServiceImpl() {
		gameCharacterStorableDAO = DomainDAO.getDao(GameCharacterStorableDAO.class);
	}

	public List<AppGameCharacter> getList() throws DomainException {
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();

		List<GameCharacterStorable> queryResult = gameCharacterStorableDAO.getAllByOwner(user);

		List<AppGameCharacter> result = new ArrayList<AppGameCharacter>(queryResult.size());
		for (GameCharacterStorable gcSto: queryResult) {
			AppGameCharacter e =  new AppGameCharacter(
					gcSto.getOrder().longValue(),
					gcSto.getName(),
					gcSto.getGender(),
					gcSto.getCreationDate(),
					gcSto.getGameDate()
			);

			result.add(e);
		}

		return result;

	}

	@Override
	public AppGameCharacter create(AppGameCharacter gc) throws DomainException {
		log.info("create("+gc.getName()+","+gc.getGender()+")");
		AppGameCharacter result;
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		
		GameCharacterStorable gcSto = gameCharacterStorableDAO.create(gc.getName(),gc.getGender(),user);

		result =  new AppGameCharacter(
				gcSto.getOrder().longValue(),
				gcSto.getName(),
				gcSto.getGender(),
				gcSto.getCreationDate(),
				gcSto.getGameDate()
		);

		return result;
	}

	@Override
	public boolean delete(AppGameCharacter gc) throws DomainException {
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();

		try {
			gameCharacterStorableDAO.delete(gc.getOrder(),user);
			log.info("deleted : "+gc.getOrder());
			return true;
		} catch (DomainException e) {
			return false;
		}
	}

}
